<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="login-title">云盘登录</div>
      </template>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" @keyup.enter="submitForm(loginFormRef)"></el-input>
        </el-form-item>
        <el-form-item label="密&nbsp;&nbsp;码" prop="password">
          <el-input v-model="loginForm.password" placeholder="请输入密码" show-password @keyup.enter="submitForm(loginFormRef)"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(loginFormRef)">登录</el-button>
          <el-button @click="resetForm(loginFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const loginFormRef = ref(null)
const router = useRouter()


const loginForm = reactive({
  username: '',
  password: ''
})

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
})

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      // 模拟登录逻辑
      if (loginForm.username === 'admin' && loginForm.password === '123456') {
        ElMessage.success('登录成功')
        // 保存用户登录状态
        localStorage.setItem('userInfo', JSON.stringify(loginForm))
        // 使用预加载脚本中暴露的 API 发送登录成功事件
        if (window.electronAPI && window.electronAPI.sendLoginSuccess) {
          window.electronAPI.sendLoginSuccess();
        } else {
          console.error('Electron API not available in this environment');
        }
        // 跳转到云盘主界面
        router.push('/dashboard')
      } else {
        ElMessage.error('用户名或密码错误')
      }
    }
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.login-card {
  width: 400px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
}
</style>